import os

from playwright.sync_api import Page

from utils.decode_image import decode_image


class FulanPage:
    """
    复深蓝页面
    """
    # 用户名-输入框
    _username = "input[name=username]"
    # 密码-输入框
    _password = "input[name=password]"
    # 验证码-图片
    _validateCodeImg = "img#validateCodeImg"
    # 验证码-输入框
    _captcha = "input[name=captcha]"
    # 登录-按钮
    _loginBtn = ".loginbtn"

    """
    页面方法层
    """

    def __init__(self, page: Page):
        self.page = page

    def verify(self):
        """
        识别验证码
        """
        image_path = os.path.dirname(os.path.dirname(__file__)) + '\\image'
        pic_path = image_path + '\\verifyCode.png'
        # 获取验证码截图
        self.page.locator(self._validateCodeImg).screenshot(path=pic_path)
        # 输入识别的验证码
        self.page.locator(self._captcha).fill(decode_image(pic_path))

    def login(self, username, password):
        """
        登录
        """
        self.page.goto('https://erp.fulan.com.cn/admin/login')
        self.page.wait_for_load_state()
        self.page.locator(self._username).fill(username)
        self.page.locator(self._password).fill(password)
        if self.page.locator(self._validateCodeImg).is_visible():
            while True:
                # 识别验证码
                self.verify()
                # 点击登录
                self.page.locator(self._loginBtn).click()
                # 等待页面加载
                self.page.wait_for_timeout(2000)
                if self.page.locator(self._validateCodeImg).is_hidden():
                    break
        else:
            # 点击登录
            self.page.locator(self._loginBtn).click()
        # 查看页面状态
        self.page.wait_for_timeout(5000)
        return self
